
const api = require('../../../ws_micro_shop/utils/api.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;
const { loadingMiddleware } = require('../../common/utils/util');
const { wxappjump } = require('../../api/common');
const { qyWXCheckSeesion } = require('../../../common/utils/ws/ws-wxwork');

Page({
  data: {
    type: 1,
    _switch: 0,
    page: 1,
    keyword: '',
    isEmpty: true,
    // toView: 'item-1',
    curr: -1,
    sort: 0,
    sort_type: -1,
    isTotalShow: false,
    isHidden: false,
    // isScrollShow: false,
    // status_type: 0,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '该页面暂无商品',
    },
    height: wx.systemInfo.windowHeight,
    cat_style: [],
    isShow: false,
    list: [],
    recentList: [
      {
        name: '不限',
        id: 0,
      },
      {
        name: '新品',
        id: 1,
      },
      {
        name: '热销',
        id: 2,
      },
      {
        name: '限时折扣',
        id: 3,
      },
      {
        name: '秒杀',
        id: 4,
      },
      {
        name: '拼团',
        id: 5,
      },
    ],
    data: {},
    cat_id: 0,
    currentnum: 0,
    isData: false,
    loadingText: '下拉加载',
    imgUrl: app.imgUrl,
    canPullUp: true,
    label_tag:'',
    share_modal_active: '',
    imgUrl: app.imgUrl
  },
  onLoad(opts) {
    wx.hideShareMenu();
    let options = opts || {};
    this.setData({
      opts,
      type: options.type || '',
      is_guide: options.is_guide || '',
      currentnum: options.id || '',
      id: options.id || '',
      isShow: true,
      isData: false,
      list: [],
      stroeId: app.ws_micro_shop_globalData.shopid,
      rolesId: app.ws_micro_shop_globalData.guide_id,
      isSaas: app.ws_micro_shop_globalData.isSaas,
    }, () => {
      app.isWXWork && qyWXCheckSeesion({});
      this.loadStart();
      this.loadCatStyle();
    });
  },
  getSearchContent() {
    let keyword = this.data.keyword;
    this.setData({
      list: [],
      isData: false,
      isHidden: false
    });
    this.loadGoodsList(keyword);
  },

  clearTxt() {
    this.setData({
      keyword: '',
      page: 1,
      list: [],
      isEmpty: true,
      isData: false,
      isHidden: false
    });
    this.loadGoodsList('');
  },
  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      keyword: e.detail.value
    });
  },

  getPosition(e) {
    let dataset = e.currentTarget.dataset;
    this.setData({
      ...dataset,
      [`data.currentnum`]: dataset.id,
      isShow: dataset.currentnum === 0 ? true : Boolean(dataset.currentnum),
    });
  },
  getChangeType(e) {
    let dataset = e.currentTarget.dataset;
    let isTotalShow = this.data.isTotalShow;
    this.setData({
      status_type: dataset.id,
      page: 1,
      isTotalShow: !isTotalShow,
      _switch: 0,

    });
    this.loadStart();
  },
  sortClick(e) {
    let _this = this;
    let { isTotalShow, isHidden } = _this.data;
    let sort = Number(e.currentTarget.dataset.sort);
    let default_sort_type = !e.currentTarget.dataset.default_sort_type ? -1 : e.currentTarget.dataset.default_sort_type;
    let sort_type = _this.data.sort_type;
    // if (sort === 0) {
    //   isTotalShow = !isTotalShow;
    // } else {
    //   isTotalShow = false;
    // }
    // if (sort === 3) {
    //   isScrollShow = !isScrollShow;
    // } else {
    //   isScrollShow = false;
    // }
    if (sort === 4) {
      isHidden = !isHidden;
    } else {
      isHidden = false;
    }
    if (Number(_this.data.sort) === sort) {
      if (Number(default_sort_type) === -1 && sort !== 4) {
        return;
      }
      if (Number(_this.data.sort_type) === -1) {
        sort_type = default_sort_type;
      } else {
        sort_type = (Number(sort_type) === 0 ? 1 : 0);
      }
    } else {
      sort_type = default_sort_type;
    }

    _this.setData({
      sort,
      sort_type,
      isHidden,
      isTotalShow,
      _switch: 0,
      page: 1,
    });

    sort !== 4 && _this.setData({
      list: [],
      isData: false,
    });
    (sort !== 4) && _this.loadStart();
  },
  chooseCateType(e) {
    let dataset = e.currentTarget.dataset;
    this.setData({
      curr: dataset.opt,
      cat_id: dataset.id,
      page: 1,
      _switch: 0,
    });
  },
  submit() {
    this.setData({
      isTotalShow: false,
      isHidden: false,
      page: 1,
      _switch: 0,
    });
    this.loadStart();
  },
  loadCatStyle() {
    let _this = this;
    const { stroeId: shop_id = '' } = this.data;
    app.ws_micro_shoprequest({
      url: api.staff.category_list,
      data: {
        shop_id,
      },
      success: function (res) {
        if (res.code === 0) {
          _this.setData({
            cat_style: res.data.list,
          });
        }
      },
    });
  },
  loadStart() {
    let _this = this;
    let { cat_id, sort, sort_type, data, status_type, currentnum, stroeId: shop_id = '' } = _this.data;
    data.shop_id = shop_id;
    data.page = 1;
    data.is_integral = 0;
    data.sort = sort;
    data.sort_type = sort_type;
    cat_id && (data.cat_id = cat_id);
    data.currentnum = currentnum;
    if (data.currentnum && data.currentnum > 3) {
      data.cat_id = 0;
      _this.setData({
        curr: -1,
        // toView: 'item-1',
      });
    }
    status_type && (data.status_type = status_type);
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.guide.goods_list,
      data: data,
      success: function (res) {

        if (res.code === 0 && res.data.list && res.data.list.length > 0) {
          _this.setData({
            list: res.data.list,
          });
        } else {
          _this.setData({
            list: [],
          });
        }
      },
      complete: res => {
        this.setData({
          isData: true,
        }, () => {
          loadingMiddleware.after(res.data, this);
          wx.hideLoading();
        });
      },
    });
  },
  loadGoodsList(keyword) {
    let _this = this;
    let { cat_id, sort, sort_type, data, status_type, currentnum, stroeId: shop_id = '' } = _this.data;
    // if (Number(type) === 1) {
    //   data.page = 1;
    //   data.c_type = 1;
    // } else if (Number(type) === 2) {
    //   data.page = 1;
    //   data.is_integral = 0;
    //   data.sort = sort;
    //   data.sort_type = sort_type;
    //   cat_id && (data.cat_id = cat_id);
    //   data.currentnum = currentnum;
    //   if (data.currentnum && data.currentnum > 3) {
    //     data.cat_id = 0;
    //     _this.setData({
    //       curr: -1,
    //       toView: 'item-1',
    //     });
    //   }
    //   data.keyword = keyword;
    //   status_type && (data.status_type = status_type);
    // } else {
    //   data.page = 1;
    //   data.from_guide = 1;
    // }
    data.shop_id = shop_id;
    data.page = 1;
    data.is_integral = 0;
    data.sort = sort;
    data.sort_type = sort_type;
    cat_id && (data.cat_id = cat_id);
    data.currentnum = currentnum;
    if (data.currentnum && data.currentnum > 3) {
      data.cat_id = 0;
      _this.setData({
        curr: -1,
        // toView: 'item-1',
      });
    }
    data.keyword = keyword;
    status_type && (data.status_type = status_type);
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.guide.goods_list,
      data: data,
      success: function (res) {
        wx.hideLoading();
        if (res.code === 0 && res.data.list && res.data.list.length > 0) {
          if(!res.data.list.label_tag){
            _this.setData({
              list: res.data.list,
              label_tag:100,
            });
          }else{
          _this.setData({
            list: res.data.list,
          });
          }
        } else {
          _this.setData({
            list: [],
          });
        }

      },
      complete: res => {
        this.setData({
          isData: true,
        });
      },
    });
  },
  onReachBottom() {
    let { page, canPullUp } = this.data;
    console.info('------page------', page);
    if (canPullUp) {
      this.setData({
        page: ++page,
      }, () => {
        this.loadmore();
      });
    }
  },
  loadmore() {
    let { list, page, cat_id, sort, sort_type, data, status_type, stroeId: shop_id = '' } = this.data;

    data.shop_id = shop_id;
    data.page = page;
    data.is_integral = 0;
    data.sort = sort;
    data.sort_type = sort_type;
    cat_id && (data.cat_id = cat_id);
    if (data.currentnum && data.currentnum > 3) {
      data.cat_id = 0;
      this.setData({
        curr: -1,
        // toView: 'item-1',
      });
    }
    status_type && (data.status_type = status_type);
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });

    loadingMiddleware.before(this);
    app.ws_micro_shoprequest({
      url: api.guide.goods_list,
      data,
      success: res => {
        if (res && res.code === 0) {
          const newList = res.data.list;
          if (newList.length <= 0) {
            this.setData({
              canPullUp: false,
              loadingText: '—— 到底啦 ——',
            });
            return;
          }
          this.setData({
            list: [...list, ...newList],
          }, () => {
            loadingMiddleware.after(res, this);
          });
        }
      },
      fail: res => {
        loadingMiddleware.after(res, this);
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },
  onUserOpStatistic: function (e) {
    //if (e.op == 'share') {
      let path = e.path;
      let { label_tag } = this.data;
      let share_type = Number(label_tag);
      this.shareCollect(share_type);
    //}
  },
  onShareAppMessage(e) {
    wx.showLoading({
      title: '正在加载',
    });
    if (e.from === 'button') {
      let dataset = e.target.dataset;
      this.setData({
        ...dataset,
      });
      let _this = this;
      let { param_id, goods, stroeId = '', rolesId = '', label_tag='' } = _this.data;
      let share_type = Number(label_tag);
      let url = share_type === 5 ? '/ws_micro_shop_pt/pages/pt/details/details?gid=' : (share_type === 4 ? '/ws_micro_shop_ms/pages/miaosha/details/details?id=' : '/ws_micro_shop/pages/goods/goods?id=');
      let path = url + param_id + '&guide_id=' + rolesId + '&shopid=' + stroeId;
      path = util.spliceSharePath(path, '4', moduleName);
      let title = goods.name;
      let imageUrl = goods.pic_url || goods.cover_pic;
      return {
        path,
        title: title,
        imageUrl: imageUrl,
      };
    }
  },
  onNavigate(e) {
    let { url = '', ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  },
  shareCollect(share_type) {
    let _this = this;
    let { param_id } = _this.data;
    app.ws_micro_shoprequest({
      url: api.staff.share_submit,
      data: {
        type: share_type,
        param_id: param_id,
      },
      method: 'post',
      success: function (res) {
        if (Number(res.code) !== 0) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: () => {
          wx.hideLoading();
      },
    });
  },
  collectFormId(e) {
    app.collectFormId(e);
  },

  onMask(e) {
    const { name = '' } = e.currentTarget.dataset;
    this.setData({
      [name]: false,
    });
  },

  showShareModal(e) {
    let dataset = e.target.dataset;
    this.setData({
      ...dataset,
      share_modal_active: 'active',
    });
  },

  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },

  wxappJump() {
    let { titletype, param_id, stroeId = '', rolesId = '', label_tag='', path } = this.data;
    let share_type = Number(label_tag) === 6 ? 0 : Number(label_tag);
    let appid =  wx.getStorageSync('appid');
    path = path + '&guide_id=' + rolesId + '&shopid=' + stroeId + '&num=' + share_type;
    wxappjump(appid, path, Number(label_tag), param_id, this);
  },

  getGoodsQrcode() {
    let _this = this;
    let { param_id = '', rolesId = '', label_tag='', goods_qrcode = '', goods } = _this.data;
    let share_type = Number(label_tag);
    _this.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.staff.goods_qrcode,
      data: {
        goods_id: param_id,
        guide_id: rolesId,
        share_type: share_type,
        cover_pic: goods.cover_pic || goods.pic_url || ''
      },
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            goods_qrcode: res.data.pic_url,
          });
          _this.shareCollect(share_type);
        }
        if (res.code === 1) {
          _this.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
    // gatherAction &&
    //   gatherAction('userGetGoodsQrcode', 'success', { goodsID: this.data.id });
  },

  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      share_modal_active: '',
      goods_qrcode: ''
    });
  },
  saveGoodsQrcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          _this.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
    // gatherAction &&
    //   gatherAction('userSaveGoodsQrcode', 'success', { goodsID: this.data.id });
  },
  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },

  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
});
